<?php
namespace app\admin\controller;


use app\common\model\Roleauthorities;

/**
 * 角色管理
 * Class Realdata
 * @package app\gygt\controller
 */
class Sysauthorities extends Admin
{

    /**
     * 给角色分配权限
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function auth_lst(){
        $page = input('page');
        $limit = input('limit');

        if(!$page){$page = 1;}
        if(!$limit){ $limit = 20; }

        $role_id = input('role_id');
        if(empty($role_id)){
            json_error_msg("角色ID不能为空，请检查！");
        }

        $auth_model = new Authorities();
        //获取所有权限列表

        $auth_model->alias('a')
            ->join('sys_menu b','a.authority = b.authority','LEFT');
        $lst = $auth_model->order('sort_number')->select();


        $count = $auth_model->count();
        //获取是否选中
        $role_auth_model = new Roleauthorities();
        $role_auth_lst = $role_auth_model->where(array('role_id'=>$role_id))->select();

        foreach ($lst as &$temp){
            $temp['checked'] = 0 ;
            foreach ($role_auth_lst as $authtemp){
                if($authtemp['authority_id'] == $temp['authority_id']){
                    $temp['checked'] = 1 ;
                    break;
                }
            }
        }

        $resObj = array();
        $resObj['lst'] = $lst;
        $resObj['totall'] = $count;
        json_success_msg($resObj);
    }

    public  function  add_role_auth(){
        $roleId = input('role_id');
        $authIds = input('authids');

        if(empty($roleId)){
            json_error_msg("权限ID不能为空，请检查！");
        }
        if(empty($authId)){
            json_error_msg("请传递权限路径");
        }

        $role_auth_model = new Roleauthorities();

        $role_auth_model->where(array('role_id'=>$roleId))->delete();
        $authId_arr = explode(',',$authIds);
        foreach ($authId_arr as $temp){
            $data['role_id'] = $roleId;
            $data['authority_id'] = $authId;
            $res = $role_auth_model->insert($data);
        }
        json_success_msg($res);
    }

    /**
     * 取消 角色对应的权限
     */
    public function  del_role_auth(){
        $roleId = input('role_id');
        $authId = input('authid');

        if(empty($roleId)){
            json_error_msg("权限ID不能为空，请检查！");
        }
        if(empty($authId)){
            json_error_msg("请传递权限路径");
        }

        $data['role_id'] = $roleId;
        $data['authority'] = $authId;

        $role_auth_model = new Roleauthorities();
        $res = $role_auth_model->where($data)->delete();
        json_success_msg($res);
    }


}
